<template>
  <div class="chatroom">
    <el-badge  class="item">
      <el-button @click="drawer = true" type="primary" style="margin-left: 16px;">
        聊天室
      </el-button>
    </el-badge>
    <el-drawer
      title="我是标题"
      :visible.sync="drawer"
      :with-header="false">

      <div style="padding: 20px 20px 18px 20px;">
        <el-row style="text-align: left">
          <span>搜索联系人：</span>
          <el-input style="width: 160px;padding-right: 20px;padding-left: 10px"
                    placeholder="请输入内容"
                    v-model="input">
          </el-input>
          <el-button icon="el-icon-search" circle @click="getLinkMan"></el-button>
        </el-row>

      </div>

      <!--左栏联系人-->
      <el-container style="height: 720px">
        <el-aside width="80px">
          <div v-for="(item,i) in linkman" :key="item.id" style="height: 60px" >
            <el-tooltip placement="left" >
              <div slot="content">{{item.username}}</div>
              <el-button @click="geToChatWindow(item)" :class="styles[i]" >
                <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
              </el-button>
              <!--<el-button @click="geToChatWindow(item)" :class="styles[i]" >{{item.username | ellipsis}}</el-button>-->
            </el-tooltip>
          </div>
        </el-aside>


        <el-container>

          <el-main>
            <wxChat
              :data="wxChatData"
              :showShade="false"
              :contactNickname="talker.username"
              :getUpperData="getUpperData"
              :getUnderData="getUnderData"
              :ownerAvatarUrl="ownerAvatarUrl"
              :contactAvatarUrl="contactAvatarUrl"
              :width="width">
            </wxChat>
          </el-main>


          <el-footer>
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="请输入内容"
              v-model="textarea"
              style="padding-top: 20px;padding-bottom: 20px">
            </el-input>
            <el-row>
              <el-button type="primary" round @click="sendMess()">发送</el-button>
              <el-button type="danger" round @click="qingKong()">清空</el-button>
            </el-row>

          </el-footer>


        </el-container>
      </el-container>


    </el-drawer>

  </div>

</template>

<script>

  import wxChat from './wxChat.vue'

  let url = 'http://localhost:8888/';
  export default {
    name: "ChatRoom",
    filters: {
      ellipsis(value) {
        if (!value) return ''
        if (value.length > 2) {
          return value.slice(0, 2) + '...'
        }
        return value
      }
    },

    data() {
      return {
        webSocket:'',


        textarea: '',
        input: '',
        linkman: [],
        talker:'',
        drawer: false,
        styles: ['selected_b'],


        upperTimes: 4,
        underTimes: 5,
        upperId: 0,
        underId: 6,
        width: 200,
        ownerAvatarUrl: require('../../../src/assets/wyz.jpg'),
        contactAvatarUrl: require('../../../src/assets/avatar2.png'),
        wxChatData: []
      };
    },
    components: {wxChat},
    created() {
      this.initWidth();
    },
    methods: {

      initWidth() {
        var ua = navigator.userAgent;
        var ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
          isIphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
          isAndroid = ua.match(/(Android)\s+([\d.]+)/),
          isMobile = isIphone || isAndroid;
        //非移动端设置400px宽度，移动端是100%
        if (!isMobile) {
          this.width = 337
        }
      },
      //向上滚动加载数据
      getUpperData() {
        var me = this;

        // 这里为模拟异步加载数据
        // 实际上你可能要这么写:
        // return axios.get('xxx').then(function(result){
        //     return result;  //result的格式需要类似下面resolve里面的数组
        // })
        return new Promise(function (resolve) {
          setTimeout(function () {
            //模拟加载完毕
            if (me.upperTimes > 3) {
              return resolve([]);
            }

            //加载数据
            resolve([{
                direction: 2,
                id: me.upperId - 1,
                type: 1,
                content: '向上滚动加载第 ' + me.upperTimes + ' 条！',
                ctime: new Date().toLocaleString()
              },
                {
                  direction: 1,
                  id: me.upperId - 2,
                  type: 1,
                  content: '向上滚动加载第 ' + me.upperTimes + ' 条！',
                  ctime: new Date().toLocaleString()
                }]
            )
          }, 1000);
          me.upperId = me.upperId + 2;
          me.upperTimes++;
        })
      },

      getUnderData() {
        var me = this;

        //意义同getUpperData()
        return new Promise(function (resolve) {
          setTimeout(function () {
            //模拟加载完毕
            if (me.underTimes > 3) {
              return resolve([]);
            }

            //加载数据
            resolve(
              [{
                direction: 1,
                id: me.underId + 1,
                type: 1,
                content: '向下滚动加载第 ' + me.underTimes + ' 条！',
                ctime: new Date().toLocaleString()
              },
                {
                  direction: 2,
                  id: me.underId + 2,
                  type: 1,
                  content: '向下滚动加载第 ' + me.underTimes + ' 条！',
                  ctime: new Date().toLocaleString()
                }]
            )
          }, 1000);

          me.underId = me.underId + 2;
          me.underTimes++;
        })
      },

      changeTimeFormat(val){
        let d = new Date(val);
        return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
      },
      timestampToTime (cjsj) {
        var date = new Date(cjsj) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-'
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
        var D = date.getDate() + ' '
        var h = date.getHours() + ':'
        var m = date.getMinutes() + ':'
        var s = date.getSeconds()
        return Y+M+D+h+m+s
      },
      qingKong() {
        this.textarea = '';
      },
      getLinkMan() {

        //发请求，通过input获取联系人信息
        this.$http
          .get(url + "user/findUserByUsername", {params: {username: this.input}})
          .then(result => {
            console.log("成功")
            this.$message({
              type: 'success',
              message: '添加联系人成功！!'
            });
            //打开聊天窗口
            this.talker = result
            this.geToChatWindow(result.body)

          }, function () {
            console.log("失败")
            this.$message({
              type: 'error',
              message: '查询无此用户！！'
            });
          });
      },
      //将联系人置顶，并且打开窗口
      geToChatWindow(item) {

        if(item!=null){
          for (var i = 0; i < this.linkman.length; i++) {
            if (this.linkman[i].id === item.id) {
              this.linkman.splice(i, 1);
              // this.linkman[i].count = 0;
              break;
            }
          }
          this.linkman.unshift(item)
        }
        this.talker = this.linkman[0]
        let id2 = this.talker.id
        //打开窗口
        this.$http
          .get(url + "user/getChatData", {params: {id1: this.$store.state.user.id, id2: id2}})
          .then(result => {
            for (let i = 0; i < result.body.length; i++) {
              result.body[i].ctime = this.changeTimeFormat(result.body[i].ctime)
              // result.body[i].id = i
              // 加上就出错
            }
            // this.wxChatData = result.body
            this.$set(this,'wxChatData',result.body)

            //发请求 更改 wxChatData
            this.textarea = ''
          }, function () {
            console.log("失败")
            // this.$message({
            //   type: 'error',
            //   message: '返回聊天记录失败！！'
            // });

          });
      },

      //初始化 左边栏 联系人
      initLinkManList(id) {
        this.$http
          .get(url + "user/getLinkMan/" + id)
          .then(result => {
            //发请求 更改 wxChatData textarea = ''
            this.linkman = result.body
            this.geToChatWindow(null)
            this.talker = this.linkman[0]
          }, function () {
            console.log("失败")
            // this.$message({
            //   type: 'error',
            //   message: '返回聊天记录失败！！'
            // });

          });
      },
      sendMess() {
        // this.textarea  传到后台，保存  附一个id,再传回来，一个map
        //将信息存入数据库
        this.$http
          .get(url + "user/addChatData", {params: {
              direction: 2,
              type: 1,
              content: this.textarea,
              uid:this.$store.state.user.id,
              lid:this.talker.id,
              linkName:this.talker.username
            }})
          .then(message => {
            //将聊天记录存到数据库后，返回到前端，并且返回
            // 下面的对象根据message调整显示出来
            // TODO
            let val = message
            message.body.ctime = this.changeTimeFormat(message.body.ctime)
            this.wxChatData.push(message.body)

            //对方接受到，与未接收到，需要设置表示，在后台判断接收对象是否下线
            val.body.linkName = this.$store.state.user.username
            this.webSocket.send(JSON.stringify(val));

            this.textarea = ''
          }, function () {
            console.log("失败")
            // this.$message({
            //   type: 'error',
            //   message: '返回聊天记录失败！！'
            // });

          });
        this.textarea = ''
      },
      initWebsocket(id) {
        let that = this
        if ("WebSocket" in window)
        {
          this.webSocket = new WebSocket("ws://localhost:8888/user/websocket/"+id);

          //连通之后的回调事件
          this.webSocket.onopen = function()
          {
            //webSocket.send( document.getElementById('username').value+"已经上线了");
            console.log("已经连通了websocket");
            // setMessageInnerHTML("已经连通了websocket");
          };

          //接收后台服务端的消息
          this.webSocket.onmessage = function (evt)
          {
            // 将接受的数据 展示出来,
            // TODO
            let a = JSON.parse( evt.data)
            a.ctime = that.timestampToTime(JSON.parse(evt.data).ctime)
            console.log(a)

            if(that.linkman[0].id===a.lid){
              that.wxChatData.push(a)
            }else{
              that.linkman.unshift({id:a.lid,username:a.linkname})
              that.talker = {id:a.lid,username:a.linkname}
              that.wxChatData = []
              that.wxChatData.push(a)
            }

          };

          //连接关闭的回调事件
          this.webSocket.onclose = function()
          {
            console.log("连接已关闭...");
            // setMessageInnerHTML("连接已经关闭....");
          };
        }
        else{
          // 浏览器不支持 WebSocket
          alert("您的浏览器不支持 WebSocket!");
        }
      },
    },
    mounted() {
      this.initLinkManList(this.$store.state.user.id);
      this.initWebsocket(this.$store.state.user.id)
    }
  };


</script>

<style scoped>

  .chatroom{
    position:absolute;
    top: 80px;
    right: 30px ;
  }
  .weiDu{
    background: yellow;
  }
  .selected_b {
    color: red;
    background: red;
  }

  .el-footer {
    background-color: #B3C0D1;
    color: #333;
    flex: 1;
  }

  .el-aside {
    background-color: #D3DCE6;
    color: #333;

  }

  .el-main {
    background-color: #E9EEF3;
    color: #333;
    flex: 3;
    padding: 0px;

  }

  .el-header {
    text-align: center;
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

</style>
<style >
  * {
    margin: 0;
    padding: 0;
  }
  h1, h2 {
    font-weight: normal;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
  }

</style>
